/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败
class MyPromise {    
    constructor(executor) {
        //  Promise状态，默认为pending
        this.status = PENDING;
        // 成功的值
        this.value = undefined;
        // 失败的值
        this.reason = undefined;
        // 成功回调，数组形式为了可以执行多次then
        this.successCallback = [];
        // 失败回调
        this.failCallback = [];
        try {
            // 传入执行函数，放到外部执行这个内部的resolve和reject函数
            executor(this.resolve, this.reject);
        } catch(e) {
            this.reject(e);
        }
    }
    // 使用箭头函数，避免this指向错误
    resolve = (value) => {
        // 如果状态不是等待 阻止程序向下执行
        if(this.status !== PENDING) return;
        this.status = FULFILLED;
        this.value = value;
        // 
        while(this.successCallback.length) this.successCallback.shift()();
    }
    reject = (reason) => {
        // 如果状态不是等待 阻止程序向下执行
        if (this.status !== PENDING) return;
        this.status = REJECTED
        this.reason = reason;
        while(this.failCallback.length) this.failCallback.shift()();
    }
    then(successCallback, failCallback) {
        successCallback = successCallback ? successCallback : value => value;
        failCallback = failCallback ? failCallback : value => value;
        let promise2 = new MyPromise((resolve, reject) => {
            if (this.status === FULFILLED) {
                myAsync(() => {
                    let x = successCallback(this.value);
                    resolvePromise(promise2, x, resolve, reject);
                }, reject);
            } else if (this.status === REJECTED) {
                myAsync(() => {
                    let x = failCallback(this.reason);
                    resolvePromise(promise2, x, resolve, reject);
                }, reject);
            } else {
                this.successCallback.push(() => {
                    myAsync(() => {
                        let x = successCallback(this.value);
                        resolvePromise(promise2, x, resolve, reject);
                    }, reject);
                });
                this.failCallback.push(() => {
                    myAsync(() => {
                        let x = failCallback(this.reason);
                        resolvePromise(promise2, x, resolve, reject);
                    }, reject);
                });
            }
        });
        return promise2;
    }
    catch(failCallback) {        
        return this.then(undefined, failCallback);
    }
    finally(callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value);
        }, reason => {
            return MyPromise.resolve(callback()).then(() => {throw reason});
        });
    }
    static all (array) {
        let result = [];
        let index = 0;
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value;
                index++;
                if (index === array.length) {
                    resolve(result);
                }
            }
            for(let i = 0; i < array.length; i++) {
                let current = array[i];
                if (current instanceof MyPromise) {
                    current.then(value => addData(i, value), reason => reject(reason));
                } else {
                    addData(i, array[i]);
                }
            }
        })
    }
    static resolve(value) {
        if (value instanceof MyPromise) return value;
        return new MyPromise(resolve => resolve(value));
    }
}

const resolvePromise = (promise2, x, resolve, reject) => {
    if (x === promise2) {
        return reject(new TypeError(''))
    }
    if (x instanceof MyPromise) {
        x.then(resolve, reject);
    } else {
        resolve(x);
    }
}

const myAsync = (resolve, reject) => setTimeout(() => {
    try {
        resolve();
    } catch(e) {
        reject(e);
    }
}, 0);

module.exports = MyPromise;